import React, { useState, useEffect } from 'react'
import { Tree } from 'antd'
import { IUdFormItem, http } from '@/lib'
import apis from '@/apis/RolePermissions'
import _ from 'lodash'

export default function SourceTree(props: ISourceTreeProps) {
  const [treeData, setTreeData] = useState([])
  const [userPermiss, setUserPermiss] = useState([])
  const [expandedKeys, setExpandedKeys] = useState([])
  useEffect(() => {
    /* 获取权限数据 */
    const { url } = props
    http.get(url, {params: {roleId: props.roleId}}).then(res=>{
      const data = res.data
      const nodes = frormatAuthTree(data)
      const { checkedKeys,expandedKeys,allCheckedKeys } = getSelectKey(data)
      console.log(nodes, checkedKeys,allCheckedKeys)
      setTreeData(nodes)
      setUserPermiss(checkedKeys)
      setExpandedKeys(expandedKeys)
      props.onChange(checkedKeys)
      props.onCheck(allCheckedKeys)
    })
    return () => {
      setTreeData([])
      setUserPermiss([])
    };
  }, [props.roleId])
  /* 处理获取的数据为treeData格式 */
  const frormatAuthTree = (auths) => {
    if (!_.isArray(auths) || auths.length === 0) {
      return auths
    }
    let treeNodes = []
    auths.map(auth=>{
      const { items: children, text: title, id: key } = auth
      let treeNode = { key, title, children }
      treeNode.children = frormatAuthTree(children)
      treeNodes.push(treeNode)
    })
    return treeNodes
  }
  /* 处理选中和展开数据 */
  const getSelectKey = (arr)=>{
    let checkedKeys:any = []
    let expandedKeys:any = []
    let allCheckedKeys:any = []
    arr.forEach(item => {
      let id = String(item.id)
      let children = item.items
      let obj:any = { checkedKeys: [], expandedKeys: [] }

      if (children && children.length > 0) {
        obj = getSelectKey(children)
        checkedKeys = [...checkedKeys, ...obj.checkedKeys]
        expandedKeys = [...expandedKeys, ...obj.expandedKeys]
        allCheckedKeys = [...allCheckedKeys, ...obj.allCheckedKeys]
      }
      if (item.isSelect) {
        allCheckedKeys.push(id)
        //子项存在选中项时 checkedKeys（选中项）不添加，expandedKeys（展开项）添加
        if (obj.checkedKeys.length === 0) {
          checkedKeys.push(id)
        } else {
          expandedKeys.push(id)
        }
      }
    })
    return { checkedKeys, expandedKeys, allCheckedKeys }
  }

  const onCheck = (checkedKeys, e) => {
    setUserPermiss(checkedKeys)
    props.onChange(checkedKeys)
    const halfCheckedKeys = e.halfCheckedKeys||[]
    // 半选中状态需要提交
    const allCheckedKeys = [...checkedKeys,...halfCheckedKeys]
    props.onCheck(allCheckedKeys)
  }
  const onExpand = (expandedKeys, e) => {
    setExpandedKeys(expandedKeys)
  }
  
  return (
    <div>
      <Tree
        checkable={true}
        checkedKeys={userPermiss}
        expandedKeys={expandedKeys}
        treeData={treeData}
        onExpand={onExpand}
        onCheck={onCheck}
      >
      </Tree>
    </div>
  )
}

interface ISourceTreeProps extends Partial<IUdFormItem> {
  // id: any
  // onChange?: (values) => void
  roleId: string
  url: string
  onCheck: (keys:string[]) => void
}
